<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="pd.showSearch">
        <el-form :model="pd.queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="产品名称" prop="name">
            <el-input v-model="pd.queryParams.name" placeholder="请输入产品名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="编码" prop="spu">
            <el-input v-model="pd.queryParams.spu" placeholder="请输入编码" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="是否商城商品" prop="isShop">
            <el-select v-model="pd.queryParams.isShop" placeholder="请选择是否商城商品" clearable>
              <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.name" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="是否销售模块" prop="isCrm">
            <el-select v-model="pd.queryParams.isCrm" placeholder="请选择是否销售模块" clearable>
              <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.name" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['wms:group:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="pd.single" @click="handleUpdate()" v-hasPermi="['wms:group:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="pd.multiple" @click="handleDelete()" v-hasPermi="['wms:group:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['wms:group:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="pd.showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="pd.loading" :data="pd.groupList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="id" align="center" prop="id" v-if="true" />
        <el-table-column label="产品名称" align="center" prop="name" />
        <el-table-column label="编码" align="center" prop="spu" />
        <el-table-column label="是否商城商品" align="center" prop="isShop">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.isShop" />
          </template>
        </el-table-column>
        <el-table-column label="是否销售模块" align="center" prop="isCrm">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.isCrm" />
          </template>
        </el-table-column>
        <el-table-column label="是否启用" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="sys_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="产品分类" align="center" prop="treeValue">
          <template #default="scope">
            <dict-tag :options="wms_product_tree" :value="scope.row.treeValue" />
          </template>
        </el-table-column>
        <el-table-column label="商城分类" align="center" prop="mallMenuId" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column fixed="left" label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                       v-hasPermi="['wms:group:edit']">修改
            </el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row.id)"
                       v-hasPermi="['wms:group:remove']">删除
            </el-button>
            <el-button link type="primary" icon="Briefcase" @click="groupEdit(scope.row)"
                       v-hasPermi="['wms:group:remove']">绑定产品
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="pd.total>0" :total="pd.total" v-model:page="pd.queryParams.pageNum"
                  v-model:limit="pd.queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改产品分组对话框 -->
    <el-dialog :title="pd.dialog.title" v-model="pd.dialog.visible" width="800px" append-to-body>
      <el-form ref="groupFormRef" :model="pd.form" :rules="pd.rules" label-width="100px">
        <el-row>
          <el-col :span="10">
            <el-form-item label="产品名称" prop="name">
              <el-input v-model="pd.form.name" placeholder="请输入产品名称" />
            </el-form-item>
            <el-form-item label="编码" prop="spu">
              <el-input v-model="pd.form.spu" placeholder="请输入编码" />
            </el-form-item>
            <el-form-item label="产品属性名" prop="attrValueName">
              <el-input v-model="pd.form.attrValueName" placeholder="请输入产品属性名" clearable style="width: 240px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="是否商城商品" prop="isShop">
              <el-select v-model="pd.form.isShop" placeholder="请选择是否商城商品">
                <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.name"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="pd.form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="是否销售模块" prop="isCrm">
              <el-select v-model="pd.form.isCrm" placeholder="请选择是否销售模块">
                <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.name"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="产品分类" prop="treeValue">
              <TreeSelect dictType="wms_product_tree" v-model:dictValue="pd.form.treeValue" placeholder="请选择产品分类"/>
            </el-form-item>
            <el-form-item label="商城分类" prop="mallMenuId">
              <el-tree-select
                v-model="pd.form.mallMenuId"
                :data="pd.menuList"
                :props="defaultProps"
                check-strictly
                :render-after-expand="false"
                clearable
              />
            </el-form-item>
            <el-form-item label="是否启用" prop="status">
              <el-radio-group v-model="pd.form.status">
                <el-radio
                    v-for="dict in sys_status"
                    :key="dict.value"
                    :label="dict.value"
                >{{dict.name}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="pd.buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 产品组 -->
    <el-dialog :title="pd.group.groupDialog.title" v-model="pd.group.groupDialog.visible" width="1000" append-to-body>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button icon="Plus" type="success" @click="submitGroupProduct">保存单据</el-button>
        </el-col>
        <el-col :span="1.5">
          <ProductSearch :searchType="2" :params="{isStock:true}" @ok="lineAdd" title="产品查询" dataText="新增一行" />
        </el-col>
        <el-col :span="1.5">
          <el-button icon="Close" type="info" @click="pd.group.groupDialog.visible = false">关闭</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button icon="Refresh" @click="getGroupList">刷新</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="pd.group.loading" :data="pd.group.groupLine">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="物品名称" align="center" prop="productName" />
        <el-table-column label="物品Id" align="center" prop="productId" />
        <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Delete" @click="delLine(scope.row)" v-hasPermi="['wms:warehouseProduct:del']">删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="pd.group.lineTotal>0"
        :total="pd.group.lineTotal"
        v-model:page="pd.group.queryLineParams.pageNum"
        v-model:limit="pd.group.queryLineParams.pageSize"
        @pagination="getGroupList"
      />
    </el-dialog>
  </div>
</template>

<script setup name="Group" lang="ts">
import {
  GroupVO,
  listGroup,
  getGroup,
  delGroup,
  addGroup,
  updateGroup,
  getGroupLine,
  groupProduct, delGroupProduct, addGroupProduct
} from '@/views/wms/group/api';
import TreeSelect from "@/views/system/dict/treeSelect.vue";
import ProductSearch from "@/views/wms/product/search.vue";
import {ProductVO} from "@/views/wms/product/api";
import {listMenu, mallMenu} from "@/views/mall/api";
import {OrderLineVO} from "@/views/wms/order/api";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_status, wms_product_tree, sys_yes_no } = toRefs<any>(proxy?.useDict('sys_status', 'wms_product_tree', 'sys_yes_no'));

const queryFormRef = ref<ElFormInstance>();
const groupFormRef = ref<ElFormInstance>();

const defaultProps = {
  label: 'name',
  value: 'id',
  children: 'children',
}

const initFormData: GroupVO = {
  name: undefined,
  spu: undefined,
  isShop: undefined,
  isCrm: undefined,
  status: undefined,
  treeValue: undefined,
  mallMenuId: undefined,
  remark: undefined,
}
const pd = reactive({
  groupList: <GroupVO[]>([]),
  menuList: <mallMenu[]>([]),
  buttonLoading: false,
  loading: true,
  showSearch: true,
  selectVO: <GroupVO[]>([]),
  single: true,
  multiple: true,
  total: 0,
  form: <GroupVO>{...initFormData},
  queryParams: <GroupVO>{
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    spu: undefined,
    isShop: undefined,
    isCrm: undefined,
    params: {
    }
  },
  rules: <ElFormRules>{
    name: [
      { required: true, message: "产品名称不能为空", trigger: "blur" }
    ],
    spu: [
      { required: true, message: "编码不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "是否启用不能为空", trigger: "change" }
    ],
  },
  dialog: <DialogOption>{
    visible: false,
    title: ''
  },
  group: {
    loading: false,
    groupId: 0,
    groupLine: <groupProduct[]>([]),
    groupLineForm: <groupProduct[]>([]),
    groupDialog: <DialogOption>{
      visible: false,
      title: '产品预警设置'
    },
    lineTotal: 0,
    queryLineParams: <groupProduct>{
      pageNum: 1,
      pageSize: 10,
    },
  },
});

// const { queryParams, form, rules } = toRefs(data);

/** 查询产品分组列表 */
async function getList() {
  pd.loading = true;
  const res = await listGroup(pd.queryParams);
  pd.groupList = res.rows;
  pd.total = res.total;
  pd.loading = false;
}

/** 取消按钮 */
function cancel() {
  reset();
  pd.dialog.visible = false;
}

/** 表单重置 */
function reset() {
  pd.form = {...initFormData};
  groupFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
function handleQuery() {
  pd.queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: GroupVO[]) {
  pd.selectVO = selection;
  pd.single = selection.length != 1;
  pd.multiple = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  pd.dialog.visible = true;
  pd.dialog.title = "添加产品分组";
}

/** 修改按钮操作 */
async function handleUpdate(row?: GroupVO) {
  reset();
  const data = row || pd.selectVO[0]
  Object.assign(pd.form, data);
  pd.dialog.visible = true;
  pd.dialog.title = "修改产品分组";
}

/** 提交按钮 */
function submitForm() {
  groupFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      pd.buttonLoading = true;
      if (pd.form.id) {
        await updateGroup(pd.form).finally(() =>  pd.buttonLoading = false);
      } else {
        await addGroup(pd.form).finally(() =>  pd.buttonLoading = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      pd.dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
async function handleDelete(row?: GroupVO) {
  const _ids = row?.id || pd.selectVO.map(v => v.id);
  await proxy?.$modal.confirm('是否确认删除产品分组编号为"' + _ids + '"的数据项？').finally(() => pd.loading = false);
  await delGroup(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
function handleExport() {
  proxy?.download('wms/group/export', {
    ...pd.queryParams
  }, `group_${new Date().getTime()}.xlsx`)
}

//添加产品
function groupEdit(row: any){
  pd.group.groupId = row.id;
  pd.group.groupLine = [];
  pd.group.groupDialog.title = '产品关联设置';
  pd.group.groupDialog.visible = true;
  pd.group.groupDialog.title = row.name + '：' + pd.group.groupDialog.title;
  getGroupList();
}

async function getGroupList(){
  pd.group.loading = true;
  pd.group.queryLineParams.groupId = pd.group.groupId;
  await getGroupLine(pd.group.queryLineParams).then((res:any) => {
    pd.group.groupLine = res.rows;
    pd.group.lineTotal = res.total;
  }).finally(()=> {
    pd.group.loading = false;
  });
}

/** 删除产品组子表信息 */
async function delLine(row: groupProduct) {
  if (pd.group.groupLineForm.includes(row)) {
    const index = pd.group.groupLine!.indexOf(row);
    pd.group.groupLine!.splice(index, 1);
    return;
  }
  proxy?.$modal.confirm('确认删除此产品信息？').then(function () {
    const bo: groupProduct = {};
    bo.productId = row.productId;
    bo.groupId = row.groupId;
    delGroupProduct(bo);
  }).then(() => {
    getGroupList();
    proxy.$modal.msgSuccess("删除成功");
  });
}

/** 提交按钮 */
async function submitGroupProduct() {
  pd.group.groupLine.forEach(val=>{
    val.groupId = pd.group.groupId;
  })
  await addGroupProduct(pd.group.groupLine).then((res: any) => {
    proxy?.$modal.msgSuccess(res.msg);
  })
  pd.group.groupDialog.visible = false;
  await getGroupList();
}

/** 新增一行 */
async function lineAdd(vo: ProductVO[]) {
  let line: groupProduct = {};
  vo.forEach((v, i, a) => {
    line.productId = v.id as number;
    line.productName = v.name;
    const findObj = pd.group.groupLine.find(item => {
      if (item.productId == line.productId)return item;
    })
    if (!findObj){
      pd.group.groupLineForm.push(line);
      pd.group.groupLine.push(line);
    }
  });
}

/** 查询菜单列表 */
async function getMenuList() {
  pd.queryParams.params = {};
  const res = await listMenu();
  pd.menuList = res.rows;
  pd.menuList = proxy?.handleTree<mallMenu>(res.rows, "id", "parentId", "children") as mallMenu[];
}

onMounted(() => {
  getList();
  getMenuList();
});
</script>
